<template>
  <div class="upload-container">
    <el-row type="flex" justify="center">
      <el-col :span="12">
        <div class="upload-section">
          <h2 class="upload-title">数据库上传</h2>

          <!-- SQL文件上传 -->
          <el-card shadow="hover" class="upload-card">
            <div slot="header">
              <span style="font-size: 18px;">🔗 SQL文件上传</span>
            </div>

            <!-- 文件上传区域 -->
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :show-file-list="false"
              accept=".sql">
              <div v-if="selectedFile" class="file-preview">
                <i class="el-icon-document"></i>
                <div class="file-details">
                  <div class="file-name">{{ selectedFile.name }}</div>
                  <div class="file-size">{{ fileSizeMB }} MB</div>
                </div>
              </div>
              <div v-else class="upload-area">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将SQL文件拖到此处，或<em>点击上传</em>
                  <div class="el-upload__tip">支持.sql格式文件，大小不超过100MB</div>
                </div>
              </div>
            </el-upload>

            <!-- 上传按钮和取消按钮 -->
            <div v-if="selectedFile" class="upload-actions">
              <el-button 
                type="primary" 
                @click="handleUpload"
                :loading="uploading">
                {{ uploading ? '上传中...' : '开始上传' }}
              </el-button>
              <el-button @click="clearFile">取消</el-button>
            </div>

            <!-- 状态提示 -->
            <div v-if="uploadStatus" class="status-message">
              <el-alert :title="uploadStatus" :type="statusType" show-icon />
            </div>
          </el-card>
      <!-- 新增函数依赖部分 -->
      <div v-if="DBid" class="fd-section">
            <el-button 
              type="primary" 
              @click="showAddFDSection = !showAddFDSection"
              icon="el-icon-circle-plus-outline">
              添加函数依赖集
            </el-button>

            <!-- 函数依赖输入区域 -->
            <div v-if="showAddFDSection" class="fd-input-area">
              <div v-for="(fd, index) in fdData" :key="index" class="fd-item">
                <el-select
                  v-model="fd.lhs"
                  placeholder="选择左部属性"
                  multiple
                  clearable
                  class="fd-select"
                >
                  <el-option
                    v-for="attr in atData"
                    :key="attr.asid"
                    :label="attr.attributename"
                    :value="attr.attributename"
                  />
                </el-select>

                <span class="arrow">→</span>

                <el-select
                  v-model="fd.rhs"
                  placeholder="选择右部属性"
                  clearable
                  class="fd-select"
                >
                  <el-option
                    v-for="attr in atData"
                    :key="attr.asid"
                    :label="attr.attributename"
                    :value="attr.attributename"
                  />
                </el-select>

                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="removeFD(index)"
                  class="delete-btn"
                />
              </div>

              <div class="fd-actions">
                <el-button 
                  type="success" 
                  @click="addNewFD"
                  icon="el-icon-plus">
                  新增依赖项
                </el-button>
                <el-button 
                  type="primary" 
                  @click="submitFD"
                  :loading="submitting">
                  {{ submitting ? '提交中...' : '提交函数依赖' }}
                </el-button>
              </div>
            </div>
          </div>
          <!-- 分隔线 
          <div class="divider">
            <span class="divider-text">或</span>
          </div>-->

          <!-- 数据库连接表单 
          <el-card shadow="hover" class="connection-card">
            <div slot="header">
              <span style="font-size: 18px;">🌐 数据库连接</span>
            </div>

            <el-form ref="form" :model="connection" label-width="120px">
              <el-form-item label="数据库类型">
                <el-select v-model="connection.type" placeholder="请选择">
                  <el-option label="MySQL" value="mysql"></el-option>
                  <el-option label="PostgreSQL" value="postgresql"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="主机地址">
                <el-input v-model="connection.host"></el-input>
              </el-form-item>

              <el-form-item label="端口号">
                <el-input-number v-model="connection.port" :min="1" :max="65535"></el-input-number>
              </el-form-item>

              <el-form-item label="用户名">
                <el-input v-model="connection.username"></el-input>
              </el-form-item>

              <el-form-item label="密码">
                <el-input v-model="connection.password" show-password></el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="connectDB">测试连接</el-button>
              </el-form-item>
            </el-form>
          </el-card>-->
    
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { upload } from '@/api/upload';
import { getattributes } from '@/api/at'; 
import { createfd } from '@/api/fd'; 
import { mapGetters } from 'vuex';

export default {
  name: 'DatabaseUpload',
  computed: {
    ...mapGetters(['token']),
    fileSizeMB() {
      return this.selectedFile ? (this.selectedFile.size / 1024 / 1024).toFixed(2) : 0;
    }
  },
  data() {
    return {
      selectedFile: null, // 当前选中的文件
      uploading: false, // 上传状态
      uploadStatus: '', // 上传结果提示
      statusType: 'info', // 提示类型
      atData: [],
      DBid: '',
      showAddFDSection: false,
      fdData: [], // 新增函数依赖数据
      submitting: false,
      connection: {
        type: 'mysql',
        host: 'localhost',
        port: 3306,
        username: '',
        password: ''
      }
    };
  },
  methods: {
    // 文件选择后的处理
    handleFileChange(file) {
      const isSQL = file.name.endsWith('.sql');
      const isLt100M = file.size / 1024 / 1024 < 100;

      if (!isSQL) {
        this.showError('只能上传SQL文件!');
        return;
      }
      if (!isLt100M) {
        this.showError('文件大小不能超过100MB!');
        return;
      }

      this.selectedFile = file.raw; // 保存选中的文件
      this.uploadStatus = ''; // 清空状态提示
    },

    // 开始上传
    async handleUpload() {
      if (!this.selectedFile) {
        this.showError('请先选择文件');
        return;
      }

      this.uploading = true;
      const formData = new FormData();
      formData.append('file', this.selectedFile);

      try {
        const response = await upload(formData);
        this.DBid = response.data.data.dbId;

        if (response.code === 20000) {
          this.showSuccess('文件上传成功！');
          setTimeout(() => {
            this.clearFile(); // 清空文件
          }, 10000);
        } else {
          this.showError(response.message || '上传失败');
        }
      } catch (error) {
        this.showError(`上传失败：${error.response?.data?.message || error.message}`);
      } finally {
        this.uploading = false;
      }

      // 获取属性数据
      getattributes(this.DBid).then(response => {
        this.atData = response.data.at;
      }).catch(error => {
        console.log(error);
      });
    },

    // 清空文件
    clearFile() {
      this.selectedFile = null;
      this.uploadStatus = '';
    },

    // 显示成功提示
    showSuccess(msg) {
      this.uploadStatus = msg;
      this.statusType = 'success';
      setTimeout(() => (this.uploadStatus = ''), 3000);
    },

    // 显示错误提示
    showError(msg) {
      this.uploadStatus = msg;
      this.statusType = 'error';
      setTimeout(() => (this.uploadStatus = ''), 3000);
    },

    // 数据库连接逻辑
    connectDB() {
      console.log('测试连接', this.connection);
    },

    // 新增方法
    addNewFD() {
      this.fdData.push({
        lhs: [],
        rhs: '',
        dbid: this.DBID
      });
    },

    removeFD(index) {
      this.fdData.splice(index, 1);
    },

    async submitFD() {
      // 验证数据
      if (this.fdData.length === 0) {
        this.$message.error('请至少添加一个函数依赖');
        return;
      }

      for (const fd of this.fdData) {
        if (fd.lhs.length === 0 || !fd.rhs) {
          this.$message.error('所有依赖项必须填写完整');
          return;
        }
      }

      this.submitting = true;
      try {
        const payload = this.fdData.map(fd => ({
          lhs: fd.lhs.join(','),
          rhs: fd.rhs,
          dbid: this.DBid
        }));

        const response = await createfd(payload);
        if (response.code === 20000) {
          this.$message.success('函数依赖提交成功');
          this.fdData = []; // 清空数据
          this.showAddFDSection = false;
          setTimeout(() => {
            this.$store.dispatch('user/setDBId', this.DBid).then(_ => {
                   this.$router.push('/DBII/db')
               })
          }, 2000); // 2000毫秒 = 2秒
        } else {
          this.$message.error(response.message || '提交失败');
        }
      } catch (error) {
        this.$message.error(`提交失败：${error.message}`);
      } finally {
        this.submitting = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.upload-container {
  padding: 40px 20px;
  min-height: calc(100vh - 84px);
  background: #f5f7fa;

  .upload-section {
    max-width: 1000px; /* 修改窗格宽度 */
    margin: 0 auto;
  }

  .upload-title {
    text-align: center;
    color: #303133;
    margin-bottom: 40px;
    font-size: 28px;
  }

  .upload-card,
  .connection-card {
    margin-bottom: 30px;
    border-radius: 8px;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }

  .divider {
    position: relative;
    margin: 25px 0;
    text-align: center;

    &-text {
      display: inline-block;
      padding: 0 15px;
      background: #f5f7fa;
      color: #909399;
      font-size: 14px;
      position: relative;
      z-index: 1;
    }

    &:before {
      content: "";
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      border-top: 1px solid #dcdfe6;
    }
  }

  .status-message {
    margin-top: 20px;
  }

  .file-preview {
    padding: 20px;
    text-align: center;
    .el-icon-document {
      font-size: 40px;
      color: #409eff;
      margin-bottom: 10px;
    }
    .file-details {
      margin-top: 10px;
      .file-name {
        font-size: 14px;
        color: #303133;
        margin-bottom: 5px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .file-size {
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .upload-actions {
    margin-top: 15px;
    text-align: center;
    button {
      margin: 0 8px;
    }
  }

  .fd-section {
    margin-top: 30px;
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .fd-input-area {
      margin-top: 20px;
    }

    .fd-item {
      display: flex;
      align-items: center;
      margin-bottom: 15px;

      .fd-select {
        flex: 1;
        margin-right: 10px;
      }

      .arrow {
        margin: 0 15px;
        font-size: 18px;
        color: #409eff;
      }

      .delete-btn {
        margin-left: 15px;
      }
    }

    .fd-actions {
      margin-top: 20px;
      text-align: center;

      button {
        margin: 0 10px;
      }
    }
  }

  ::v-deep .el-upload-dragger {
    padding: 40px 20px;
    background-color: #fafafa;
    border: 2px dashed #e0e0e0;
    border-radius: 8px;

    &:hover {
      border-color: #409eff;
    }
  }
}
</style>